package com.abc.recycling.controller;

import com.abc.recycling.domain.Message;
import com.abc.recycling.service.MessageService;
import com.abc.recycling.service.UserService;
import com.abc.recycling.common.Result;
import lombok.RequiredArgsConstructor;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.Collections;
import java.util.List;

@Controller
@RequestMapping("/message")
@RequiredArgsConstructor
public class MessageController {

    private final MessageService messageService;
    private final UserService userService;

    /**
     * 消息列表页面
     */
    @GetMapping("/list")
    public String list(
            @RequestParam(required = false) String type,
            @RequestParam(required = false) Integer status,
            @RequestParam(required = false) String keyword,
            @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime startTime,
            @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime endTime,
            @RequestParam(defaultValue = "1") Integer currentPage,
            @RequestParam(defaultValue = "10") Integer pageSize,
            Authentication authentication,
            Model model
    ) {
        try {
            Long userId = userService.getUserByUsername(authentication.getName()).getId();
            List<Message> messages = messageService.searchMessages(userId, type, status, keyword, startTime, endTime);
            
            // 添加分页相关的变量
            model.addAttribute("currentPage", currentPage);
            model.addAttribute("pageSize", pageSize);
            model.addAttribute("totalPages", (messages.size() + pageSize - 1) / pageSize);
            model.addAttribute("messages", messages);
            
            // 添加未读消息数量
            int unreadCount = messageService.getUnreadCount(userId);
            model.addAttribute("unreadCount", unreadCount);
            
            return "message/list";
        } catch (Exception e) {
            model.addAttribute("error", "获取消息列表失败：" + e.getMessage());
            return "error";
        }
    }

    /**
     * 获取未读消息数量
     */
    @GetMapping("/unread/count")
    @ResponseBody
    public int getUnreadCount(Authentication authentication) {
        try {
            Long userId = userService.getUserByUsername(authentication.getName()).getId();
            return messageService.getUnreadCount(userId);
        } catch (Exception e) {
            return 0;
        }
    }

    /**
     * 获取未读消息列表
     */
    @GetMapping("/unread")
    @ResponseBody
    public List<Message> getUnreadMessages(Authentication authentication) {
        try {
            Long userId = userService.getUserByUsername(authentication.getName()).getId();
            return messageService.getUnreadMessages(userId);
        } catch (Exception e) {
            return Collections.emptyList();
        }
    }

    /**
     * 标记消息为已读
     */
    @PostMapping("/{id}/read")
    @ResponseBody
    public Result<?> markAsRead(@PathVariable Long id) {
        try {
            messageService.markAsRead(id);
            return Result.success();
        } catch (Exception e) {
            return Result.error("标记消息已读失败：" + e.getMessage());
        }
    }

    /**
     * 删除消息
     */
    @DeleteMapping("/{id}")
    @ResponseBody
    public void delete(@PathVariable Long id) {
        messageService.deleteMessage(id);
    }
    
    /**
     * 批量标记消息为已读
     */
    @PostMapping("/batch/read")
    @ResponseBody
    public void batchMarkAsRead(@RequestBody List<Long> ids) {
        messageService.markMessagesAsRead(ids);
    }
    
    /**
     * 批量删除消息
     */
    @DeleteMapping("/batch")
    @ResponseBody
    public void batchDelete(@RequestBody List<Long> ids) {
        messageService.deleteMessages(ids);
    }
} 